package com.sunny.feign.custom;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 动态代理类 调用服务
 *
 * @author Sunny
 * @date 2020/2/24
 */
public class RequestMappingInvocationHandler implements InvocationHandler {

    private String serviceName;
    private BeanFactory beanFactory;

    public RequestMappingInvocationHandler(String serviceName, BeanFactory beanFactory) {
        this.serviceName = serviceName;
        this.beanFactory = beanFactory;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        GetMapping getMapping = AnnotationUtils.findAnnotation(method, GetMapping.class);
        if (getMapping != null) {
            String[] uri = getMapping.value();

            //组装url
            StringBuilder urlBuilder = new StringBuilder("http://").append(serviceName).append(uri[0]).append("?");

            int parameterCount = method.getParameterCount();
            Class<?>[] paramTypes = method.getParameterTypes();
            Annotation[][] paramAnno = method.getParameterAnnotations();
            Annotation[] annotations = paramAnno[0];
            StringBuilder queryString = new StringBuilder();
            //组装参数
            for (int i = 0; i < parameterCount; i++) {
                RequestParam requestParam = (RequestParam) annotations[i];
                String paramName = requestParam.value();
//                Class<?> paramType = paramTypes[i];
                String paramValue = String.valueOf(args[i]);
                queryString.append("&").append(paramName).append("=").append(paramValue);
            }

            String url = urlBuilder.append(queryString).toString();
            RestTemplate restTemplate = this.beanFactory.getBean("loadBalanceRestTemplate", RestTemplate.class);
            return restTemplate.getForObject(url, method.getReturnType());
        }
        return null;
    }

}
